package com.qf.zuul.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.http.HttpServletRequest;

@Component
public class CheckTokenFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return FilterConstants.PRE_TYPE;   // 前置过滤器
    }

    @Override
    public int filterOrder() {
        return FilterConstants.PRE_DECORATION_FILTER_ORDER - 1;  // 指定前置过滤器的顺序
    }

    @Override
    public boolean shouldFilter() {
        return true;   // 开启当前过滤器
    }


    @Override
    public Object run() throws ZuulException {
        // 请求发送过来时,在请求参数中携带key为token的一个值,这个值必须等于123
        //1. 获取request对象
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();

        //2. 获取到token的值
        String token = request.getParameter("token");

        //3. 做判断,如果没有token或者token不等于123
        if(StringUtils.isEmpty(token) || !"123".equalsIgnoreCase(token)) {
            //4. 停止请求继续访问下一个过滤器,直接给页面返回错误码
            context.setSendZuulResponse(false);                                     // 请求不继续执行
            context.setResponseStatusCode(HttpStatus.UNAUTHORIZED.value());         // 响应错误码
        }
        return null;   // 不管,意义不大
    }
}
